import cv2
import numpy as np

# 读取图片
image = cv2.imread('6.jpg')

# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 应用Canny边缘检测
edges = cv2.Canny(gray, 100, 200)

# 查找轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

# 遍历轮廓并找到最大的轮廓
max_contour = max(contours, key=cv2.contourArea)

# 计算轮廓的边界矩形
rect = cv2.minAreaRect(max_contour)

# 获取旋转矩阵
box = cv2.boxPoints(rect)
box = np.int0(box)

# 旋转图像
rotated_image = cv2.drawContours(image, [box], 0, (0, 255, 0), 2)

# 显示图像
cv2.imshow('Rotated Image', rotated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()